package fi.foyt.cs.persistence.dao.oauth;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import fi.foyt.cs.persistence.dao.GenericDAO;
import fi.foyt.cs.persistence.domainmodel.oauth.AuthenticatedUser;

public class AuthenticatedUserDAO extends GenericDAO<AuthenticatedUser> {

  public AuthenticatedUser create(String userId, String grantedScopes) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      AuthenticatedUser authenticatedUser = new AuthenticatedUser();
      authenticatedUser.setUserId(userId);
      authenticatedUser.setGrantedScopes(grantedScopes);
      entityManager.persist(authenticatedUser);
      entityManager.getTransaction().commit();
      return authenticatedUser;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }
  
  public AuthenticatedUser findByUserId(String userId) {
    EntityManager entityManager = getEntityManager();
    Query query = entityManager.createQuery("select o from AuthenticatedUser o where userId = :userId");
    query.setParameter("userId", userId);
    return getSingleResult(query);
  }

  public AuthenticatedUser updateGrantedScopes(AuthenticatedUser authenticatedUser, String grantedScopes) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      authenticatedUser.setGrantedScopes(grantedScopes);
      authenticatedUser = entityManager.merge(authenticatedUser);
      entityManager.getTransaction().commit();
      return authenticatedUser;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  } 
}
